package dao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
@WebServlet("/schoolRead.ctl")
public class SchoolReadCtl extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //创建JSON对象message_jsonObj,以便往前端响应信息
        JSONObject message_jsonObj = new JSONObject();
        response.setContentType("application/json;charset=UTF-8");
        //将request body转换为JSON字串
        String req_jsonStr = JSONUtil.getJSON(request);
        //将request body 解析为JSONObject对象，可能含有分页信息
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        //如果body请求为空
        if (req_jsonObj == null){
            message_jsonObj.put("message","未收到请求信息！");
            response.getWriter().println(message_jsonObj);
            return;
        }

        try {
            //读取分页信息，形成分页对象{"pagination":{"pageNo":2,"pageSize":2}}
            //将JSON字串解析为Pagination
            Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
            //从请求JSONObject对象中读取键“conditionList”对应的值，形成List<Condition>对象
            List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
            //分页获得指定的学院
            Collection<School> schools = SchoolService.getInstance().findAll(conditionList,pagination);
            String schools_json = JSON.toJSONString(
                    schools,SerializerFeature.DisableCircularReferenceDetect
            );
            message_jsonObj.put("totalNum",pagination.getTotalNum());
            message_jsonObj.put("records",schools);
            //响应message_jsonObj到前端
            response.getWriter().println(message_jsonObj);
            //response.getWriter().println(schools_json);

        } catch (SQLException e) {
            message_jsonObj.put("message","数据库操作异常");
            response.getWriter().println(message_jsonObj);
            e.printStackTrace();
        }catch (Exception e){
            message_jsonObj.put("message","网络异常");
            response.getWriter().println(message_jsonObj);
            response.getWriter().println(e.getMessage());
            e.printStackTrace();
        }
    }
}
/*
{
        "pagination":{"pageNo":2,"pageSize":2},
        "conditionList":[
        {"value":"管理","key":"description","operator":"LIKE"},
        {"value":"4","key":"uni_id","operator":"LIKE"}
        ]
        }*/
